package com.yang.news.job.jobhandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yang.news.convert.HotSearchConvert;
import com.yang.news.dao.entity.HotSearchRecord;
import com.yang.news.model.dto.HotSearchDetailDTO;
import com.yang.news.service.HotSearchRecordService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

import static com.yang.news.enums.HotSearchEnum.WEIBO;
import static com.yang.news.cache.hotSearch.HotSearchCache.CACHE_MAP;

/**
 * @author Billyang
 * @date 2024/9/19 16:46
 */
@Component
@Slf4j
public class WeiBoHotSearchJob {
    
    @Autowired
    private HotSearchRecordService hotSearchRecordService;

    @PostConstruct
    public void init(){
        try{
            hotSearch(null);
            log.info("初始化微博数据成功");
        }catch (Exception e){
            log.error("初始化微博数据异常",e);
        }
    }

    @XxlJob("weiboHotSearchJob")
    public ReturnT<String> hotSearch(String param){
        log.info("微博热搜爬虫任务开始");
        try {
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url("https://sbmy.fun/api/hotSearch/queryByType?type=weibo")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                    .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                    .header("Cache-Control", "no-cache")
                    .header("Connection", "keep-alive")
                    .header("Pragma", "no-cache")
                    .header("Sec-Fetch-Dest", "document")
                    .header("Sec-Fetch-Mode", "navigate")
                    .header("Sec-Fetch-Site", "none")
                    .header("Sec-Fetch-User", "?1")
                    .header("Upgrade-Insecure-Requests", "1")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0")
                    .header("sec-ch-ua", "\"Chromium\";v=\"128\", \"Not;A=Brand\";v=\"24\", \"Microsoft Edge\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .build();
            Response response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONArray array = jsonObject.getJSONObject("data").getJSONArray("hotSearchDTOList");
            List<HotSearchRecord> hotSearchList = Lists.newArrayList();
            for (int i = 0; i < array.size(); i++) {
                JSONObject object = array.getJSONObject(i);
                HotSearchRecord hotSearchRecord = HotSearchRecord.builder().hotSearchResource(WEIBO.getCode()).build();
                //设置文章标题
                hotSearchRecord.setHotSearchTitle(object.getString("hotSearchTitle"));
                //设置百度三方ID
                hotSearchRecord.setHotSearchId(object.getString("hotSearchId"));
                //设置文章封面
                hotSearchRecord.setHotSearchCover(object.getString("hotSearchCover"));
                //设置文章摘要
                hotSearchRecord.setHotSearchExcerpt(object.getString("hotSearchExcerpt"));
                //设置文章连接
                hotSearchRecord.setHotSearchUrl(object.getString("hotSearchUrl"));
                //设置热搜热度
                hotSearchRecord.setHotSearchHeat(object.getString("hotSearchHeat"));
                //按顺序排名
                hotSearchRecord.setHotSearchOrder(i + 1);
                hotSearchList.add(hotSearchRecord);
            }
            System.out.println(JSON.toJSONString(hotSearchList));
            if (CollectionUtils.isEmpty(hotSearchList)) {
                return ReturnT.SUCCESS;
            }
            //数据加到缓存中
            CACHE_MAP.put(WEIBO.getCode(), HotSearchDetailDTO.builder()
                    //热搜数据
                    .hotSearchDTOList(
                            hotSearchList.stream().map(HotSearchConvert::toDTOWhenQuery).collect(Collectors.toList()))
                    //更新时间
                    .updateTime(Calendar.getInstance().getTime()).build());
            //数据持久化
            hotSearchRecordService.batchSave(hotSearchList);
            log.info("微博热搜爬虫任务结束");
            return ReturnT.SUCCESS;
        } catch (IOException e) {
            log.error("获取微博数据异常", e);
        }
        return ReturnT.FAIL;
    }
}
